/**
 * 描述: 封装md5方法
 * 作者: Jack Chen
 * 日期: 2020-06-20
*/

const crypto = require('crypto'); // 引入crypto加密模块
// 加密函数
const password = 'CYbr3GXthuN8DzWU67RjbXbg4LSTgAYj'; // 密码，客户端和服务端共用

function encrypt(text) {
  const iv = crypto.randomBytes(16); // 生成16字节的随机IV
  const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(password), iv);
  let encrypted = cipher.update(text, 'utf-8', 'hex');
  encrypted += cipher.final('hex');
  return { iv: iv.toString('hex'), data: encrypted };
}

// 解密函数
function decrypt(encryptedData) {
  const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(password), Buffer.from(encryptedData.iv, 'hex'));
  let decrypted = decipher.update(encryptedData.data, 'hex', 'utf-8');
  decrypted += decipher.final('utf-8');
  return decrypted;
}

module.exports.encrypt = encrypt;
module.exports.decrypt = decrypt;